#include "jniBitmapView.h"
#include "jniHelper.h"
#include "plasma.h"
#include <android/bitmap.h>


JNIEXPORT void JNICALL JniBitmapView_updateGraphics
        (JNIEnv *env, jobject thiz, jobject zBitmap) {
    JNIEnv J = *env;
    void *bitmapPixels = NULL;
    AndroidBitmapInfo info;

    if (zBitmap == NULL) {
        LOGE("bitmap is null\n");
        return;
    }


    memset(&info, 0, sizeof(info));
    AndroidBitmap_getInfo(env, zBitmap, &info);
    // Check format, only RGB565 & RGBA are supported
    if (info.width <= 0 || info.height <= 0 ||
        (info.format != ANDROID_BITMAP_FORMAT_RGB_565 &&
         info.format != ANDROID_BITMAP_FORMAT_RGBA_8888)) {
        LOGE("invalid bitmap\n");
        J->ThrowNew(env, J->FindClass(env, "java/io/IOException"), "invalid bitmap");
        return;
    }

    // Lock the bitmap to get the buffer
    int res = AndroidBitmap_lockPixels(env, zBitmap, &bitmapPixels);
    if (bitmapPixels == NULL) {
        LOGE("fail to lock bitmap: %d\n", res);
        J->ThrowNew(env, J->FindClass(env, "java/io/IOException"), "fail to open bitmap");
        return;
    }

//    LOGE("Effect: %dx%d, %d, %p\n", info.width, info.height, info.format, bitmapPixels);
    fill_plasma(bitmapPixels, info.width, info.height, info.stride / 4);

    AndroidBitmap_unlockPixels(env, zBitmap);
}